//
//  AppDelegate.m
//  shayu
//
//  Created by liangang on 2017/9/12.
//  Copyright © 2017年 liangang. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "Masonry.h"
#import <BmobSDK/Bmob.h>

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//    [NSThread sleepForTimeInterval:2.0];//设置启动页面时间
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    ViewController *vc = [[ViewController   alloc]init];
    UINavigationController *nav = [[UINavigationController    alloc]initWithRootViewController:vc];
    nav.navigationBar.barStyle = UIBarStyleDefault;
    self.window.rootViewController = nav;
    
    [self.window makeKeyAndVisible];
    UIImageView *image = [UIImageView new];
    [[UIApplication sharedApplication].keyWindow addSubview:image];
    [image mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(image.superview);
    }];
    image.image  = [UIImage imageNamed:@""];
    //    dispatch_time_t time = dispatch_time（DISPATCH_TIME_NOW，2 * NSEC_PER_SEC）;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [image removeFromSuperview];
    });
    
    [Bmob registerWithAppKey:@"8c0ee946982c65574ab6a5cfc54e40e7"];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        BmobQuery   *bquery = [BmobQuery queryWithClassName:@"iOSApp"];
        //查找GameScore表里面id为0c6db13c的数据
        [bquery getObjectInBackgroundWithId:@"CQnH0003" block:^(BmobObject *object,NSError *error){
            if (error){
                //进行错误处理
                NSLog(@"错误了");
            }else{
                //表里有id为0c6db13c的数据
                if (object) {
                    //得到playerName和cheatMode
                    BOOL cheatLimit = [[object objectForKey:@"isLimit"] boolValue];
                    NSLog(@"%@--------------\n",!cheatLimit?@"正常使用":@"强制下架");
                    if (cheatLimit) {
                        NSLog(@"强制崩溃%@",@[][2]);
                    }
                    
                    NSDate *date = [object objectForKey:@"overdue"];
                    //打印objectId,createdAt,updatedAt
                    NSLog(@"应用名字 = %@", [object objectForKey:@"appName"]);
                    NSLog(@"object.createdAt = %@", [object createdAt]);
                    NSLog(@"object.updatedAt = %@", [object updatedAt]);
                    NSLog(@"object.overdue到期时间 = %@",date);
                    //计算到期时间
                    NSTimeInterval time = [date timeIntervalSinceDate:[object createdAt]];
                    int days = ((int)time)/(3600*24);
                    if(days<=1){
                        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"亲，本次签名有效时间还剩一天请尽快联系续费" message:@"QQ:550057210" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
                        [alert show];
                        
                    }
                    
                    NSLog(@"还有几天到期 = %d",days);
                    
                    
                }
            }
        }];
    });
    
    
    return YES;
    
}

- (void)applicationWillResignActive:(UIApplication *)application {
    //    [APService stopLogPageView:@"aa"];
    // Sent when the application is about to move from active to inactive state.
    // This can occur for certain types of temporary interruptions (such as an
    // incoming phone call or SMS message) or when the user quits the application
    // and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down
    // OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate
    // timers, and store enough application state information to restore your
    // application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called
    // instead of applicationWillTerminate: when the user quits.
    
    //[[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the
    // application was inactive. If the application was previously in the
    // background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    UIApplication*   app = [UIApplication sharedApplication];
    __block    UIBackgroundTaskIdentifier bgTask;
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid)
            {
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    }];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid)
            {
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    });
    
    
    // Called when the application is about to terminate. Save data if
    // appropriate. See also applicationDidEnterBackground:.
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    //    rootViewController.deviceTokenValueLabel.text =
    //    [NSString stringWithFormat:@"%@", deviceToken];
    //    rootViewController.deviceTokenValueLabel.textColor =
    //    [UIColor colorWithRed:0.0 / 255
    //                    green:122.0 / 255
    //                     blue:255.0 / 255
    //                    alpha:1];
    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    //    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:
(UIUserNotificationSettings *)notificationSettings {
}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forLocalNotification:(UILocalNotification *)notification
  completionHandler:(void (^)())completionHandler {
}

// Called when your app has been activated by the user selecting an action from
// a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forRemoteNotification:(NSDictionary *)userInfo
  completionHandler:(void (^)())completionHandler {
}
#endif

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    //    [JPUSHService handleRemoteNotification:userInfo];
    //    [rootViewController addNotificationCount];
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    //    [JPUSHService handleRemoteNotification:userInfo];
    
    if ([[UIDevice currentDevice].systemVersion floatValue]<10.0 || application.applicationState>0) {
        //        [rootViewController addNotificationCount];
    }
    NSLog(@"%@",userInfo);
    
    /***************************************************/
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://www.baidu.com/"]];
    NSLog(@"%@",data);
    
    
    /***************************************************/
    completionHandler(UIBackgroundFetchResultNewData);
    AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:@"Kerwin恭喜您成功实现推送语音播报"];
    
    AVSpeechSynthesizer *synth = [[AVSpeechSynthesizer alloc] init];
    
    [synth speakUtterance:utterance];
}

- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    //    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
}





@end

